package com.ly.gen.rowMapper;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.ly.gen.entity.GenField;
import com.ly.gen.utils.GenDbUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

/**
 * 字段映射器
 *
 * @author luoyun
 * @Date: 2025/6/13 18:46
 * @Note:
 */
@Slf4j
public class FieldRowMapper implements RowMapper<GenField> {
    @Override
    public GenField mapRow(ResultSet rs, int rowNum) throws SQLException {
        GenField field = GenField.builder()
                .dbIsKey("id".equalsIgnoreCase(rs.getString("column_name")) ? 1 : 0)
                .columnType(rs.getString("column_type"))
                .columnSimpleType(rs.getString("data_type"))
                .tableName(rs.getString("table_name"))
                .dbFieldName(StrUtil.toCamelCase(rs.getString("column_name").toLowerCase()))
                .dbFieldNameOld(rs.getString("column_name"))
                .dbFieldTxt(ObjUtil.isNotEmpty(rs.getString("column_comment")) ? rs.getString("column_comment") : rs.getString("column_name"))
                .dbIsNull("yes".equalsIgnoreCase(rs.getString("is_nullable")) ? 1 : 0)
                .dbLength(NumberUtil.parseInt(rs.getString("numeric_precision")))
                .dbPointLength(NumberUtil.parseInt(rs.getString("numeric_scale")))
                .fieldShowType("text")
                .fieldLength(120)
                .queryMode("single")
                .dbIsPersist(1)
                .isQuery(0)
                .isShowForm(1)
                .fieldMustInput("0")
                .isShowList(1)
                .orderNum(rs.getInt("ordinal_position"))
                .createBy("-200")
                .build();
        this.wrapperDbType(field, rs);
        log.info("当前封装结果：字段名：{}  \t字段类型：{} \t字段长度：{} \t字段java类型：{} 最大长度：{}",
                rs.getString("column_name"),
                rs.getString("data_type"),
                rs.getString("numeric_precision"),
                field.getFieldShowType(),
                rs.getString("character_maximum_length")
        );
        // this.printRs(rs);
        return field;
    }

    /**
     * 字段类型 -> java类型
     *
     * @return
     */
    public void wrapperDbType(GenField field, ResultSet rs) throws SQLException {
        String dataType = rs.getString("data_type");
        String charmaxLength = rs.getString("character_maximum_length");
        String columnName = rs.getString("column_name");
        //兼容jeecg
        if ("datetime".equals(dataType)) {
            field.setDbType("Datetime");
            field.setFieldShowType("datetime");
        } else if ("date".equals(dataType)) {
            field.setDbType("Date");
            field.setFieldShowType("date");
        } else if ("varchar".equals(dataType) || "json".equals(dataType)) {
            field.setDbType("string");
        } else if ("int".equals(dataType) || "bit".equals(dataType) || "tinyint".equals(dataType) || "bigint".equals(dataType)) {
            //todo：ly:目前long还是string，需要进一步修改
            field.setDbType("bigint".equals(dataType) ? "long" : "int");
        } else if ("decimal".equals(dataType)) {
            field.setDbType("BigDecimal");
        } else if ("blob".equals(dataType)) {
            field.setDbType("string");
            field.setFieldShowType("textarea");
            field.setDbLength(NumberUtil.parseInt(charmaxLength));
        }else{
            field.setDbType("string");
        }
        String javaType = GenDbUtils.getJavaType(dataType);
        field.setColumnJavaType(javaType);

        if (StrUtil.isNotEmpty(charmaxLength)) {
            // 大数据类型处理，包含了 longtext类型
            if (NumberUtil.parseLong(charmaxLength) >= 3000L) {
                field.setDbType("Text");
                field.setFieldShowType("textarea");
            }
            field.setDbLength(NumberUtil.parseInt(charmaxLength));
        }
        if ("id".equalsIgnoreCase(columnName)) {
            // id设置只读
            field.setDbFieldTxt("主键");
            field.setOrderNum(-1);
            field.setDbIsKey(1);
            field.setIsShowForm(0);
            field.setIsShowList(0);
            field.setIsReadOnly(1);
        } else if ("create_by".equalsIgnoreCase(columnName)
                || "create_time".equalsIgnoreCase(columnName)
                || "update_by".equalsIgnoreCase(columnName)
                || "update_time".equalsIgnoreCase(columnName)
                || "sys_org_code".equalsIgnoreCase(columnName)) {
            field.setIsShowForm(0);
            field.setIsShowList(0);
        }
    }

    /**
     * 打印ResultSet
     *
     * @param rs
     * @throws SQLException
     */
    public void printRs(ResultSet rs) throws SQLException {
        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();
        while (rs.next()) {
            String[] rowValues = new String[columnCount];
            for (int i = 1; i <= columnCount; i++) {
                rowValues[i - 1] = rs.getString(i); // 按索引获取值（兼容所有类型）
            }
            System.out.println(String.join(" | ", rowValues));
        }
    }
}
